const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const { action } = event
  
  console.log('📋 订单表结构升级云函数调用:', action)
  
  try {
    switch (action) {
      case 'upgradeSchema':
        return await upgradeOrdersSchema()
      case 'migrateData':
        return await migrateOrdersData()
      case 'validateData':
        return await validateUpgrade()
      case 'rollback':
        return await rollbackUpgrade()
      default:
        return {
          success: false,
          error: '未知的操作类型'
        }
    }
  } catch (error) {
    console.error('订单表结构升级错误:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 升级订单表结构 - 添加新字段
async function upgradeOrdersSchema() {
  console.log('🔧 开始升级订单表结构...')
  
  try {
    // 1. 创建新的索引
    await createNewIndexes()
    
    console.log('✅ 订单表结构升级完成')
    return {
      success: true,
      message: '订单表结构升级完成，新字段已准备就绪'
    }
  } catch (error) {
    console.error('❌ 订单表结构升级失败:', error)
    throw error
  }
}

// 创建新的数据库索引
async function createNewIndexes() {
  console.log('📊 创建新的数据库索引...')
  
  const indexes = [
    {
      name: 'serviceId索引',
      spec: { serviceId: 1 },
      options: { background: true }
    },
    {
      name: 'serviceCategoryCode索引', 
      spec: { serviceCategoryCode: 1 },
      options: { background: true }
    },
    {
      name: '复合索引(serviceId+status)',
      spec: { serviceId: 1, status: 1 },
      options: { background: true }
    }
  ]
  
  for (const index of indexes) {
    try {
      await db.collection('orders').createIndex(index.spec, index.options)
      console.log(`✅ ${index.name}创建成功`)
    } catch (error) {
      if (error.message.includes('already exists')) {
        console.log(`⚠️ ${index.name}已存在，跳过`)
      } else {
        console.warn(`❌ ${index.name}创建失败:`, error.message)
      }
    }
  }
}

// 迁移历史数据 - 添加服务外键
async function migrateOrdersData() {
  console.log('🔄 开始迁移历史订单数据...')
  
  try {
    // 1. 获取所有需要迁移的订单
    const ordersQuery = await db.collection('orders').where({
      serviceId: db.command.exists(false) // 没有serviceId字段的订单
    }).get()
    
    console.log(`📋 发现 ${ordersQuery.data.length} 条需要迁移的订单`)
    
    if (ordersQuery.data.length === 0) {
      return {
        success: true,
        message: '没有需要迁移的数据',
        migrated: 0
      }
    }
    
    // 2. 获取所有服务数据用于匹配
    const servicesQuery = await db.collection('services').get()
    const servicesMap = {}
    
    // 创建服务映射：分类 -> 服务列表
    servicesQuery.data.forEach(service => {
      if (!servicesMap[service.category]) {
        servicesMap[service.category] = []
      }
      servicesMap[service.category].push(service)
    })
    
    console.log(`📦 加载了 ${servicesQuery.data.length} 个服务项`)
    
    // 3. 批量迁移数据
    let migratedCount = 0
    let errorCount = 0
    
    for (const order of ordersQuery.data) {
      try {
        const updateData = await buildUpdateData(order, servicesMap)
        
        if (Object.keys(updateData).length > 0) {
          await db.collection('orders').doc(order._id).update({
            data: updateData
          })
          migratedCount++
          console.log(`✅ 订单 ${order.id} 迁移成功`)
        } else {
          console.log(`⚠️ 订单 ${order.id} 无匹配服务，跳过`)
        }
      } catch (error) {
        errorCount++
        console.error(`❌ 订单 ${order.id} 迁移失败:`, error.message)
      }
    }
    
    console.log(`🎉 数据迁移完成: 成功 ${migratedCount} 条，失败 ${errorCount} 条`)
    
    return {
      success: true,
      message: '历史数据迁移完成',
      migrated: migratedCount,
      errors: errorCount,
      total: ordersQuery.data.length
    }
  } catch (error) {
    console.error('❌ 数据迁移失败:', error)
    throw error
  }
}

// 构建更新数据
async function buildUpdateData(order, servicesMap) {
  const updateData = {}
  
  // 1. 处理serviceType关联
  if (order.serviceType) {
    updateData.serviceCategoryCode = order.serviceType
    
    // 2. 尝试匹配具体服务
    const categoryServices = servicesMap[order.serviceType] || []
    
    if (categoryServices.length > 0) {
      // 优先选择第一个服务作为默认关联
      // 后续可以根据订单描述进行更智能的匹配
      const matchedService = findBestMatchService(order, categoryServices)
      
      if (matchedService) {
        updateData.serviceId = matchedService._id
        console.log(`🎯 为订单 ${order.id} 匹配到服务: ${matchedService.title}`)
      }
    }
  }
  
  // 3. 添加迁移标记
  updateData.migrationTime = new Date()
  updateData.migrationVersion = '1.0'
  
  return updateData
}

// 智能匹配最佳服务
function findBestMatchService(order, services) {
  // 策略1: 如果只有一个服务，直接返回
  if (services.length === 1) {
    return services[0]
  }
  
  // 策略2: 根据订单描述关键词匹配
  const description = (order.description || '').toLowerCase()
  const serviceProject = (order.serviceProject || '').toLowerCase()
  
  for (const service of services) {
    const serviceTitle = (service.title || '').toLowerCase()
    const serviceDesc = (service.description || '').toLowerCase()
    
    // 检查标题匹配
    if (serviceProject && serviceTitle.includes(serviceProject)) {
      return service
    }
    
    // 检查描述匹配
    if (description && serviceDesc.includes(description.substring(0, 10))) {
      return service
    }
  }
  
  // 策略3: 返回评分最高的服务
  const bestService = services.reduce((best, current) => {
    return (current.rating || 0) > (best.rating || 0) ? current : best
  })
  
  return bestService
}

// 验证升级结果
async function validateUpgrade() {
  console.log('✅ 开始验证升级结果...')
  
  try {
    // 1. 统计总订单数
    const totalOrders = await db.collection('orders').count()
    
    // 2. 统计已关联服务的订单数
    const linkedOrders = await db.collection('orders').where({
      serviceId: db.command.exists(true)
    }).count()
    
    // 3. 统计有分类代码的订单数
    const categorizedOrders = await db.collection('orders').where({
      serviceCategoryCode: db.command.exists(true)
    }).count()
    
    // 4. 检查数据完整性
    const sampleOrders = await db.collection('orders').limit(5).get()
    
    const validation = {
      totalOrders: totalOrders.total,
      linkedOrders: linkedOrders.total,
      categorizedOrders: categorizedOrders.total,
      linkageRate: (linkedOrders.total / totalOrders.total * 100).toFixed(2) + '%',
      categorizationRate: (categorizedOrders.total / totalOrders.total * 100).toFixed(2) + '%',
      sampleData: sampleOrders.data.map(order => ({
        id: order.id,
        hasServiceId: !!order.serviceId,
        hasCategoryCode: !!order.serviceCategoryCode,
        serviceType: order.serviceType,
        migrationVersion: order.migrationVersion
      }))
    }
    
    console.log('📊 验证结果:', validation)
    
    return {
      success: true,
      message: '升级验证完成',
      validation: validation
    }
  } catch (error) {
    console.error('❌ 验证失败:', error)
    throw error
  }
}

// 回滚升级（移除新字段）
async function rollbackUpgrade() {
  console.log('🔄 开始回滚升级...')
  
  try {
    // 警告：这是危险操作
    console.warn('⚠️ 警告：即将删除升级添加的字段')
    
    // 移除新添加的字段
    const orders = await db.collection('orders').where({
      serviceId: db.command.exists(true)
    }).get()
    
    let rollbackCount = 0
    
    for (const order of orders.data) {
      await db.collection('orders').doc(order._id).update({
        data: {
          serviceId: db.command.remove(),
          serviceCategoryCode: db.command.remove(),
          migrationTime: db.command.remove(),
          migrationVersion: db.command.remove()
        }
      })
      rollbackCount++
    }
    
    console.log(`🔄 回滚完成，处理了 ${rollbackCount} 条记录`)
    
    return {
      success: true,
      message: '升级回滚完成',
      rollbackCount: rollbackCount
    }
  } catch (error) {
    console.error('❌ 回滚失败:', error)
    throw error
  }
} 